package com.webreport.webapp.handle;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.webreport.exception.ManagerException;

@Controller
public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {
	
	@ExceptionHandler(value = { IOException.class, SQLException.class, ManagerException.class })
	public String exp(Exception ex, HttpServletRequest request) {
		request.setAttribute("ex", ex);
		return "/error";
	}
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response,
			Object handler,
			Exception ex) {

		// Expose ModelAndView for chosen error view.
		String viewName = determineViewName(ex, request);
		if (viewName != null) {//JSP格式返回
			if(!(StringUtils.indexOfIgnoreCase(request.getHeader("accept"),"application/json")>-1) || (StringUtils.indexOfIgnoreCase(request.getHeader("X-Requested-With"),"XMLHttpRequest")>-1)){//如果不是异步请求
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
					return getModelAndView(viewName, ex, request);
				}
			}else{//JSON格式返回
				Map<String, Object> model=new HashMap<String, Object>();
				if(this.logger.isDebugEnabled()){
					model.put("debug", true); 
				}//exception
				model.put("msg", ex.getMessage());
				model.put("failure", true);
				try {
					response.getWriter().write("有异常啦!");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return new ModelAndView();
			}
			return null;
		}
		else {
			return null;
		}
	}
}